<template>
  <el-form ref="deptForm" label-width="120px" :model="form" :rules="rulesForm">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="(item) in employee" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartmentDetail, updateDepartment } from '@/api/departments'

export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 自定义规则 部门标签全局不能重复
    const validCode = (rule, value, callback) => {
      // 单独把code取出来
      let codeList = this.originList.map(item => item.code)
      // 如果是编辑框，从数组中删除当前的code
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // console.log(codeList, 'codeList')
      if (codeList.includes(value)) {
        callback(new Error('部门编码' + value + '已存在'))
      } else {
        callback()
      }
    }
    // 自定义规则 部门名称当前不能重复
    const validName = (rule, value, callback) => {
      // 新增框 把当前部门的所有子部门名称拿出来
      let nameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // 编辑框
      if (this.isEdit) {
        // 找到当前编辑的部门对象
        const curDepartment = this.originList.find(item => item.id === this.id)
        // 找到当前编辑的部门对象的父级部门
        const curpid = curDepartment.pid
        // 找到当前编辑的部门的兄弟部门，排除自己
        nameList = this.originList.filter(item => item.pid === curpid && item.id !== this.id).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error('部门名称' + value + '已存在')) : callback()
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      employee: [],
      rulesForm: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            pattern: /^\S{1,50}$/,
            message: '部门名称必须是1-50位的字符',
            trigger: 'blur'
          },
          { validator: validName, trigger: 'blur' }],
        code: [{ required: true, message: '请输入部门编码', trigger: 'blur' },
          {
            pattern: /^\S{1,50}$/,
            message: '部门编码必须是1-50位的字符',
            trigger: 'blur'
          },
          { validator: validCode, trigger: 'blur' }],
        manager: [{ required: true, message: '请输入部门负责人', trigger: 'blur' }],
        introduce: [{ required: true, message: '请输入部门介绍', trigger: 'blur' }, {
          pattern: /^\S{1,300}$/,
          message: '部门介绍必须是1-300位的字符',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    // 加载负责人
    this.loadEmployee()
    if (this.isEdit) {
      // 部门详情
      this.loadDepartmentDetail()
    }
  },
  methods: {
    // 清空表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    // 新增部门函数
    async doAdd() {
      try {
        await addDepartments({ ...this.form, pid: this.id })
        // 清空表单
        // 发送请求 子传父
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 新增部门
    hSubmit() {
      // 兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 如果表单验证不通过，直接return
        // 通过的代码
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 取消按钮
    hCancel() {
      // 关闭弹层
      this.$emit('close')
    },
    // 新增负责人
    async loadEmployee() {
      try {
        const res = await getEmployeeSimple()
        // console.log(res.data.data, '负责人')
        this.employee = res.data.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取子部门信息
    async loadDepartmentDetail() {
      try {
        const res = await getDepartmentDetail(this.id)
        // console.log(res, '编辑部门')
        this.form = res.data.data
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await updateDepartment(this.form)
        console.log(res.data, '编辑部门')
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>

</style>
